﻿using GMS.NET.Const;
using GMS.NET.Core.Provider.CacheProvider;

namespace GMS.NET.Application.Service.System.Import
{
    [Authorize]
    [DynamicApiController]
    public class ImportService : DbManger, IImportService
    {
        private readonly ICachingService cache = App.GetService<ICachingProvider>().GetCache(CacheType.Memory);

        [HttpPost]
        [NonUnify]
        public async Task<MemoryStream> GetExcelCheckData()
        {
            var values = new List<Dictionary<string, string>>();
            var Stream =await cache.GetAsync<MemoryStream>(UserClaimConst.CacheExcelData(UserInfo.UserId));
            if (Stream is not null)
            {
                using (var DataStream = new MemoryStream())
                {
                    Stream.Position = 0;
                    await Stream.CopyToAsync(DataStream);
                    DataStream.Position = 0;
                    values = await MiniExcelTool.GetExcelStreamToDicListAsync(DataStream);
                }
            }
            var OutStream = await MiniExcelTool.GetExcelStreamAsync(values);
            return OutStream;
        }
        [HttpPost]
        public async Task<TabularData<Dictionary<string, string>>> GetExcelData([FromBody] QueryPivot queryPivot)
        {
            var result = new List<Dictionary<string, string>>();
            var total = 0;
            var Stream =await cache.GetAsync<MemoryStream>(UserClaimConst.CacheExcelData(UserInfo.UserId));
            if (Stream is not null)
            {
                using (var DataStream = new MemoryStream())
                {
                    Stream.Position = 0;
                    await Stream.CopyToAsync(DataStream);
                    DataStream.Position = 0;
                    var DataList = await MiniExcelTool.GetExcelStreamToDicListAsync(DataStream);
                    result = DataList.Skip((queryPivot.PageIndex - 1) * queryPivot.PageSize).Take(queryPivot.PageSize).ToList();
                    total = DataList.Count;
                }
            }
            return new TabularData<Dictionary<string, string>>() { Items = result, page_Total = total };
        }
        public async Task<List<string>> UploadExcelData()
        {
            // 创建流的拷贝
            MemoryStream copiedStream = new MemoryStream();
            using (var memoryStream = new MemoryStream())
            {
                await App.HttpContext.Request.Body.CopyToAsync(memoryStream);
                memoryStream.Position = 0;
                await memoryStream.CopyToAsync(copiedStream);
                copiedStream.Position = 0;
                cache.Set(UserClaimConst.CacheExcelData(UserInfo.UserId), copiedStream, TimeSpan.FromHours(1));
                return memoryStream.Query(true).Cast<IDictionary<string, object>>().First().Keys.ToList();
            }
        }
    }
}
